<template>
  <div class = "">
    <el-form
        :inline="true"
        :model="ruleForm"
        class="advanced-form"
        label-position="right"
    >
      <el-row :gutter="20">
        <!-- 第一行 -->
        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-form-item label="用户名" class="form-item inline-form-item" >
            <el-input
                v-model="ruleForm.username"
                placeholder="请输入用户名"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-form-item label="姓名" class="form-item inline-form-item">
            <el-input
                v-model="ruleForm.realName"
                placeholder="请输入真实姓名"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-form-item label="角色" class="form-item inline-form-item">
            <el-select
                v-model="ruleForm.role"
                placeholder="请选择角色"
                clearable
                style="width: 100%"
            >
              <el-option label="农户" value="farmer" />
              <el-option label="投资者" value="investor" />
              <el-option label="审计" value="auditor" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <el-form-item label="状态" class="form-item inline-form-item">
            <el-select
                v-model="ruleForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 100%"
            >
              <el-option label="启用" value="normal" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 操作按钮（单独一行） -->
      <el-row>
        <el-col :span="24" class="form-actions">
          <el-button type="primary" @click="onSubmit" icon="el-icon-search">查询</el-button>
          <el-button
              type="success"
              @click="onAdd"
              icon="el-icon-plus"
              plain
          >新增</el-button>
        </el-col>
      </el-row>
    </el-form>

<!--  列表页  -->
    <el-table :data="tableData"
              style="width: 100%"
              :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
              stripe
              border>
      <el-table-column prop="username" label="用户名" width="180" align="center" />
      <el-table-column prop="realName" label="姓名" width="180" align="center" >
        <template slot-scope="scope">
          {{ scope.row.realName || '未填写' }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="180" align="center" >
        <template slot-scope="scope">
          {{ scope.row.phone || '未填写' }}
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色" width="180" align="center" >
        <template slot-scope="scope">
          <el-tag :type="getRoleTagType(scope.row.role)">
            {{ roleMap[scope.row.role] || '未知角色' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="180" align="center" >
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.status"
              active-value="normal"
              inactive-value="disabled"
              active-text="启用"
              inactive-text="禁用"
              @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="toDel(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    页脚-->
    <el-pagination
        background
        :page-size="pageSize"
        :current-page="pageNum"
        :page-count="pages"
        layout="prev, pager, next"
        :total="total"
        @current-change="changePageNum"
    >
    </el-pagination>

<!--    弹窗，实现新增用户信息-->
    <el-dialog
        title=  "新增"
        :visible.sync="addDialog"
        width="400px"
        :destroy-on-close = "true"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select
              v-model="ruleForm.role"
              clearable
              style="width: 100%"
          >
            <el-option label="农户" value="farmer" />
            <el-option label="投资者" value="investor" />
            <el-option label="审计" value="auditor" />
          </el-select>
        </el-form-item>

        <el-form-item >
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
          <el-button @click="addDialog = false">取 消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>


  </div>
</template>

<script>
import {deleteUser, getUserPage, saveOrUpdateUser, updateStatus} from "@/api/users";

  export default {
    data() {
      return {
        ruleForm: {
          username:"",
          realName:"",
          role: "",
          status:""
        },
        // 角色映射
        roleMap: {
          admin: '管理员',
          farmer: '农户',
          investor: '投资者',
          auditor: '审计员'
        },
        tableData: [],
        pages: 0,
        total: 1,
        pageNum: 1,
        pageSize:6,
        //添加弹窗 默认值
        addDialog: false,
        rules: {
          username: [
            { required: true, message: '请输入账号', trigger: 'blur' },
            { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
          ],
          role: [
            { required: true, message: '请选择角色', trigger: 'change' }
          ]
        }
      }
    },
    methods: {

      //获取删除id
      toDel(id) {
        console.log(id)
        this.$confirm(`确定删除该用户吗？`, '提示').then(async () => {
          // 这里调用API更新状态
          await deleteUser(id)
          this.getPage()
          this.$message.success('删除成功')
        }).catch(() => {
          this.$message.info('取消删除')
        })
      },

      // 状态切换处理
      handleStatusChange(row) {
        this.$confirm(`确定${row.status === 'normal' ? '启用' : '禁用'}该用户吗？`, '提示', {
          type: 'warning'
        }).then(() => {
          // 这里调用API更新状态
          updateStatus(row)
          this.$message.success('状态更新成功')
        }).catch(() => {
          // 取消操作时恢复原状态
          row.status = row.status === 'normal' ? 'disabled' : 'normal'
        })
      },
      // 角色标签样式
      getRoleTagType(role) {
        const typeMap = {
          admin: 'danger',
          farmer: 'success',
          investor: 'warning',
          auditor: 'primary'
        }
        return typeMap[role] || 'info'
      },

      //打开添加弹窗
      onAdd() {
        this.addDialog = true
      },

      //添加信息
      submitForm(ruleForm) {
        this.$refs[ruleForm]((valid) => {
          if(valid){
            saveOrUpdateUser(this.ruleForm).then(()=>{
              this.ruleForm = {}
              this.getPage()
              this.addDialog = false
            })
          }
        });

      },

      //查询
      onSubmit(){
        this.pageNum = 1
        this.getPage()
      },

      //获取具体一页数据
      getPage(){
        getUserPage(this.ruleForm,this.pageNum,this.pageSize).then((res) =>{
          if(res.code == 200){
            this.tableData = res.data.list
            this.pages = res.data.pages
            this.total = res.data.total
            this.pageNum = res.data.pageNum
            this.pageSize = res.data.pageSize
          }
        })
      },

      //直接选择第几页
      changePageNum(v){
        console.log(v+'')
        this.pageNum = v
        this.getPage()
      },
    },
    created(){
      this.getPage()
    }

  }
</script>

<style scoped>

.advanced-form {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 18px;
  width: 100%;
}

.inline-form-item {
  display: flex;
  align-items: center;
}

.inline-form-item ::v-deep  {
  white-space: nowrap;
  padding-right: 10px;
}

.inline-form-item ::v-deep  {
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
}


.form-actions {
  text-align: right;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
  margin-top: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-actions {
    text-align: center;
  }
  .form-actions {
    margin-bottom: 10px;
    width: 100%;
  }
}

</style>

